package com.ztom.v2;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author ZhangTao
 */
public class Code71DecodeString {

    public String decodeString(String s) {
        Deque<String[]> stack = new LinkedList<>();
        int num = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if ('0' <= s.charAt(i) && s.charAt(i) <= '9') {
                num = num * 10 + s.charAt(i) - '0';
            } else if (s.charAt(i) == '[') {
                // 入栈
                stack.addLast(new String[]{num + "", sb.toString()});
                // 重置
                num = 0;
                sb.setLength(0);
            } else if (s.charAt(i) == ']') {
                // 出栈结算
                String[] pop = stack.pollLast();
                int count = Integer.parseInt(pop[0]);
                StringBuilder tmp = new StringBuilder();
                while (count-- > 0) {
                    // 当前[]里的字符串重复 count 次
                    tmp.append(sb);
                }
                sb.setLength(0);
                // 拼接 count 数字前的字符串
                sb.append(pop[1]).append(tmp);
            } else {
                // 收集当前字符
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }


    public String decodeString1(String s) {
        return process(s, 0)[1];
    }

    public String[] process(String s, int index) {
        // 当前层 [] 的字符
        StringBuilder curStr = new StringBuilder();
        // 当前层 [] 前面的数字
        int curNum = 0;
        while (index < s.length()) {
            if ('0' <= s.charAt(index) && s.charAt(index) <= '9') {
                curNum = curNum * 10 + s.charAt(index) - '0';
            } else if (s.charAt(index) == '[') {
                // 递
                String[] process = process(s, index + 1);
                // 更新 index
                index = Integer.parseInt(process[0]);
                // 添加字符串
                while (curNum > 0) {
                    curStr.append(process[1]);
                    curNum--;
                }
            } else if (s.charAt(index) == ']') {
                // 归
                return new String[]{index + "", curStr.toString()};
            } else {
                // 记录当前字符
                curStr.append(s.charAt(index));
            }
            index++;
        }
        return new String[]{"-1", curStr.toString()};
    }
}
